/**
 * @desc token验证
 * @author Daker(Daker.zhou@gmail.com)
 */

import { Context } from "koa";
import * as console from "console";
import {Response} from "../tools/response";
// 校验token中间件
export default async (ctx: Context, next: () => Promise<any>) => {

    // 有bug,没有拦截请求成功

    try {

            // 判断是否是空token, true 为空，false 为有token
            const authorization = ctx.request.header.authorization;

            // 如果为真，表示空口令
            if (!authorization) {
                ctx.status = 403;
                throw "非法访问"
            }

            const parts = authorization.split(" ");

            if (parts.length === 2) {

                // 取出token
                const scheme = parts[0];

                if (!scheme) {
                    ctx.status = 403;
                    throw "非法访问"
                }

                if (/^authorization$/i.test(scheme)) {
                    // 放过
                    await next();
                }

            }

    } catch (e) {
        console.log(e)
        ctx.body = Response(403, e);
        return;
    }

};
